import React, { Component } from 'react'
import { Form, Switch, Input, Button, message, Radio, Spin } from 'antd'
import { connect } from 'react-redux'
import constant from 'containers/finance-setting/loan-setting/constant'
import Priority from "components/template/priority";
import Selector from "components/selector";
import { messages } from "share/common";
import Chooser from "components/chooser";
import companyAccountSettingService from '../company-account-setting.service'
import httpFetch from "share/httpFetch";

class AccountRule extends Component {

  state = {
    saveLoading: false,
    priority: null,
    showBank: null,
    baseCurrencyCode: null
  };

  handleSave = () => {
    this.props.form.validateFieldsAndScroll((err, value) => {
      if (!err) {
        const { close } = this.props, { priority, showBank, baseCurrencyCode } = this.state;
        const { record } = this.props.params;
        if (!priority) {
          message.error(messages('finance-4.key353')/*请分配权限*/);
          return -1;
        }
        value.companyId = priority.levelOrgId;
        // 以下是代码鬼才周力哥的代码 一个大对象打散传过去 而且不仅仅是打散 还要修改数据原
        value.bankName = showBank.bankName;
        value.bankCode = showBank.bankCode;
        value.bankBranchName = showBank.bankBranchName;
        value.bankKey = showBank.bankCode;
        value.city = showBank.city;
        value.bankType = showBank.bankType;
        value.cityCode = showBank.cityCode;
        value.province = showBank.province;
        value.provinceCode = showBank.provinceCode;
        value.countryCode = showBank.countryCode;
        //修改数据原
        value.accountOpeningAddress = showBank.detailAddress;
        value.bankAddress = showBank.openAccount;
        value.country = showBank.countryName;
        value.swiftCode = showBank.swiftCode;
        value.multiCurrencyPay = value.currencyCode === baseCurrencyCode ? value.multiCurrencyPay : false;
        this.setState({ saveLoading: true });
        companyAccountSettingService.saveBank(Object.assign(record, value)).then(() => {
          this.setState({ saveLoading: false }, () => {
            message.success(messages('common.operate.success')/*操作成功*/);
            close(true);
          });
        }).catch(e => {
          message.error(e.response.data.message);
          this.setState({ saveLoading: false });
        })
      }
    })
  };

  componentWillMount() {
    const { record } = this.props.params;
    const { company } = this.props;
    this.setState({
      showBank: record.hasOwnProperty('id') ? {
        bankName: record.bankName,
        bankCode: record.bankCode,
        bankBranchName: record.bankBranchName,
        bankKey: record.bankCode,
        city: record.city,
        bankType: record.bankType,
        cityCode: record.cityCode,
        province: record.province,
        provinceCode: record.provinceCode,
        countryCode: record.countryCode,
        detailAddress: record.accountOpeningAddress,
        openAccount: record.bankAddress,
        countryName: record.country,
        swiftCode: record.swiftCode
      } : null,
      baseCurrencyCode: record.baseCurrencyCode,
      priority: record.hasOwnProperty('id') ? {
        levelOrgName: record.companyName,
        levelOrgId: record.companyId
      } : {
        levelOrgName: company.name,
        levelOrgId: company.id
      }
    });
    this.handleBase()
  }

  handlePriority = value => {
    this.props.form.setFieldsValue({
      currencyCode: undefined
    });
    this.setState({ priority: value });
  };

  handleBase = (value = {}) => {
    const { company } = this.props;
    httpFetch.get(`/api/setOfBooks/${value.setOfBooksId || company.setOfBooksId}`).then(res => {
      this.setState({ baseCurrencyCode: res.data.functionalCurrencyCode });
    }).catch(e => {
      message.error(e.response.data.message)
    })
  };

  handleBankCodeChange = value => {
    this.setState({ showBank: value && value[0] ? value[0] : null })
  };

  render() {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { saveLoading, showBank, priority, baseCurrencyCode } = this.state;
    const { formItemLayout } = constant;
    const { close } = this.props, { record } = this.props.params;
    return(
      <div>
        <Form className={'new-form'}>
          <Form.Item
            label={messages('common.column.status')/*状态*/}
            {...formItemLayout}
          >
            {getFieldDecorator("enabled", {
              rules: [{ required: true, message: messages('common.please.input')/*请输入*/ }],
              valuePropName: "checked",
              initialValue: record.hasOwnProperty('id') ? record.enabled : true
            })(
              <Switch>{messages('finance-4.key344')/*启用temp*/}</Switch>
            )}
          </Form.Item>
          <Form.Item
            label={messages('finance-4.key364')/*设为默认*/}
            {...formItemLayout}
            extra={messages('finance-4.key365')/*一个公司下只能有一个默认*/}
          >
            {getFieldDecorator("defaults", {
              valuePropName: "checked",
              initialValue: record.hasOwnProperty('id') ? record.defaults : false
            })(
              <Switch/>
            )}
          </Form.Item>
          <Priority
            top={'COMPANY'}
            onChange={this.handlePriority}
            disabled={record.hasOwnProperty('id')}
            defaultValue={priority}
            onChangeRange={this.handleBase}
            formItemLayout={formItemLayout}
            single={false}
          />
          <Form.Item
            label={messages('finance-4.key50')/*银行账户账号*/}
            {...formItemLayout}
          >
            {getFieldDecorator("bankAccountNumber", {
              rules: [{ required: true, message: messages('common.please.input')/*请输入*/ }],
              initialValue: record.bankAccountNumber
            })(
              <Input placeholder={messages('finance-4.key70')/*请输入temp2*/}/>
            )}
          </Form.Item>
          <Form.Item
            label={messages('finance-4.key49')/*银行账户名称*/}
            {...formItemLayout}
          >
            {getFieldDecorator("bankAccountName", {
              rules: [{ required: true, message: messages('common.please.input')/*请输入*/ }],
              initialValue: record.bankAccountName
            })(
              <Input placeholder={messages('finance-4.key70')/*请输入temp2*/}/>
            )}
          </Form.Item>
          <Form.Item
            label={messages('common.currency')/*币种*/}
            {...formItemLayout}
          >
            {getFieldDecorator("currencyCode", {
              rules: [{ required: true, message: messages('common.select')/*请选择*/ }],
              initialValue: record.hasOwnProperty('id') ? {
                key: record.currencyCode,
                label: record.currencyCode
              } : undefined
            })(
              <Selector
                type={'currency'}
                itemMap
                dynamicUrl
                params={{ companyId: priority ? priority.levelOrgId : undefined, userOId: this.props.user.userOID }}
                disabled={!priority}
                filter={item => item.enable}
                showSearch
              />
            )}
          </Form.Item>
          {
            baseCurrencyCode && getFieldValue('currencyCode') === baseCurrencyCode && (
              <Form.Item
                label={messages('finance-4.key420')/*多币种付款*/}
                {...formItemLayout}
                extra={messages('finance-4.key421')/*启用后支持使用本币币种的银行账户支付外币币种的单据*/}
              >
                {getFieldDecorator("multiCurrencyPay", {
                  initialValue: record.hasOwnProperty('id') ? record.multiCurrencyPay : false
                })(
                  <Radio.Group options={[
                    { label: messages('common.status.enable')/*启用*/, value: true },
                    { label: messages('finance-4.key422')/*不启用*/, value: false }
                  ]}/>
                )}
              </Form.Item>
            )
          }
          <Form.Item
            label={messages('finance-4.key22')/*银行名称*/}
            {...formItemLayout}
            extra={
              showBank ? (
                <div>
                  <div>{messages('finance-4.key366')/*国家*/}:{showBank.countryName || '-'}</div>
                  <div>{messages('finance-4.key367')/*开户地*/}:{showBank.openAccount || '-'}</div>
                  <div>{messages('finance-4.key51')/*银行详细地址*/}:{showBank.detailAddress || '-'}</div>
                  <div>{messages('finance-4.key368')/*开户支行Swift Code*/}:{showBank.swiftCode || '-'}</div>
                </div>
              ) : null
            }
          >
            {getFieldDecorator("bank", {
              rules: [{ required: true, message: messages('common.select')/*请选择*/ }],
              initialValue: record.hasOwnProperty('id') ? [showBank] : undefined
            })(
              <Chooser
                single
                type="select_bank"
                locale={{emptyText: messages('finance-4.key426')/*当前条件没有搜索到银行，建议分词以提高搜索命中率，例：【工商银行深圳华侨城支行】改为【工商银行 深圳 华侨城支行】*/}}
                placeholder={messages('common.select')/*请选择*/}
                labelKey="bankBranchName"
                onChange={this.handleBankCodeChange}
                valueKey="bankCode"
              />
            )}
          </Form.Item>
          <Form.Item
            label={messages('finance-4.key369')/*账户明细*/}
            {...formItemLayout}
          >
            {getFieldDecorator("accountCode", {
              initialValue: record.accountCode
            })(
              <Input placeholder={messages('finance-4.key70')/*请输入temp2*/}/>
            )}
          </Form.Item>
          <Form.Item
            label={messages('finance-4.key63')/*备注temp*/}
            {...formItemLayout}
          >
            {getFieldDecorator("remark", {
              initialValue: record.remark
            })(
              <Input placeholder={messages('finance-4.key70')/*请输入temp2*/}/>
            )}
          </Form.Item>
          <div className='footer-operate'>
            <Button type='primary' onClick={this.handleSave}
                    loading={saveLoading}>{messages('common.ok')/*确定*/}</Button>
            <Button onClick={() => close()}>{messages('common.cancel')/*取消*/}</Button>
          </div>
        </Form>
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user
  }
}

export default connect(mapStateToProps)(Form.create()(AccountRule))
